import DlyAdminRole from '../../model/dlyadminrole'
import ApiError from '../../error/ApiError'
import ApiErrorNames from '../../error/ApiErrorNames'
class UserController {
	static async add(ctx) {
		const requestBody = ctx.request.body
		const { role_name, name } = requestBody
		if (!role_name || !name) {
			throw new ApiError(ApiErrorNames.NoParamsData)
		}
		// 检查是否存在
		const isExist = await DlyAdminRole.findOne({ name })
		if (isExist) {
			throw new ApiError(ApiErrorNames.RoleNameExist)
		}
		if (requestBody.hasOwnProperty('_id')) {
			delete requestBody._id
		}
		const result = await DlyAdminRole.create(requestBody)
		ctx.body = result

		// throw new ApiError(ApiErrorNames.RegistryUserisExist)
	}
	static async list(ctx) {
		// 获取全部数据
		const result = await DlyAdminRole.find({})
		ctx.body = { list: result, total: result.length }
	}

	static async deleted(ctx) {
		const { _id } = ctx.request.query
		if (!_id) {
			throw new ApiError(ApiErrorNames.NoParamsData)
		}
		const result = await DlyAdminRole.deleteOne({ _id })
		if (result.deletedCount === 0) {
			throw new ApiError(ApiErrorNames.NoData)
		}
		ctx.body = result
	}

	static async update(ctx) {
		// 编辑
		const requestBody = ctx.request.body
		const { _id } = requestBody
		if (!_id) {
			throw new ApiError(ApiErrorNames.NoParamsData)
		}
		delete requestBody._id
		const result = await DlyAdminRole.updateOne({ _id }, requestBody)
		if (result.nModified === 0) {
			throw new ApiError(ApiErrorNames.NoData)
		}
		ctx.body = result
	}
}

export default UserController
